package crmdna.mail;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;

import javax.inject.Named;

import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiMethod.HttpMethod;

import crmdna.common.APIResponse;
import crmdna.common.APIResponse.Status;
import crmdna.program.Program;
import crmdna.program.ProgramProp;
import crmdna.registration.Invoice;
import crmdna.registration.Registration;
import crmdna.registration.RegistrationProp;

@Api(name = "mail")
public class MailApi {

	@ApiMethod(path = "sendEDM", httpMethod = HttpMethod.POST)
	public APIResponse sendEDM(@Named("groupId") long groupId,
			@Named("contactsCSV") String contactsCSV,
			@Named("subject") String subject,
			@Named("htmlContent") String htmlContent,
			@Named("test") boolean test) {
		try {
			
			return new APIResponse(Status.SUCCESS, "success");

		} catch (Exception ex) {
			return new APIResponse(ex);
		}
	}
	
	private static void prepareEDM(String firstName, String lastName, String emailAddress) {
		
	}
	
	public static void saveSubscription(String firstName, String lastName, String emailAddress) {
		Mandrill.sendMail(
			"info@bhairaviyoga.sg", "FKfPwZmmNOyK88Abx2RaoQ", "info@bhairaviyoga.sg", "Bhairavi Yoga", "New subscription", 
			firstName + "\t" + lastName  + "\t" + emailAddress);
	}
	
	public static void sendConfirmationEmail(String client, long registrationId) {
		
		Logger logger = Logger.getLogger(MailApi.class.getName());
		
		Mail mail = prepareConfirmationEmail(client, registrationId);
		
		String apiKey = "FKfPwZmmNOyK88Abx2RaoQ";			
		String fromEmail = "info@bhairaviyoga.sg";
		String fromName = "Bhairavi Yoga";
		
		Mandrill.sendMail(mail.emailAddress, apiKey, fromEmail, fromName, mail.subject, mail.htmlContent);
	}
	
	private static Mail prepareConfirmationEmail(String client, long registrationId) {

		RegistrationProp regProp = Registration.safeGet(client, registrationId).toProp();
		ProgramProp prgProp = Program.safeGet(client, regProp.programId).toProp();
		
		Logger logger = Logger.getLogger(MailApi.class.getName());

		String startDate = String.valueOf(prgProp.startYYYYMMDD);
		String endDate = String.valueOf(prgProp.endYYYYMMDD);
		
		try {
			SimpleDateFormat ftSrc = new SimpleDateFormat("yyyyMMdd");
			SimpleDateFormat ftDst = new SimpleDateFormat("MMM d");
			
			startDate = ftDst.format(ftSrc.parse(String.valueOf(prgProp.startYYYYMMDD)));
			endDate = ftDst.format(ftSrc.parse(String.valueOf(prgProp.endYYYYMMDD)));
		}
		catch (Exception ex) {
			
		}
		
		String dates = startDate;
		if(!startDate.equalsIgnoreCase(endDate)) 
			dates = dates + " - " + endDate;
		
		Mail mail = new Mail(
				regProp.email, 
				"Registration - " + prgProp.programTypeProp.displayName + ": " + dates,
				MandrillHelper.getConfirmationEmailTemplate());
		
		mail.htmlContent = mail.htmlContent.replaceAll("%ProgramName%", prgProp.programTypeProp.displayName);
		mail.htmlContent = mail.htmlContent.replaceAll("%FirstName%", regProp.firstName);
		mail.htmlContent = mail.htmlContent.replaceAll("%LastName%", regProp.lastName);
		mail.htmlContent = mail.htmlContent.replaceAll("%RegId%", String.valueOf(registrationId));
		mail.htmlContent = mail.htmlContent.replaceAll("%EmailAddress%", regProp.email);
		mail.htmlContent = mail.htmlContent.replaceAll("%MobilePhone%", regProp.mobilePhone);
		
		if(regProp.homePhone != null) 
			mail.htmlContent = mail.htmlContent.replaceAll("%HomePhone%", regProp.homePhone);
		else
			mail.htmlContent = mail.htmlContent.replaceAll("%HomePhone%", "");
		
		if(regProp.officePhone != null) 
			mail.htmlContent = mail.htmlContent.replaceAll("%OfficePhone%", regProp.officePhone);
		else
			mail.htmlContent = mail.htmlContent.replaceAll("%OfficePhone%", "");
		
		mail.htmlContent = mail.htmlContent.replaceAll("%Dates%", startDate + " - " + endDate);		
		mail.htmlContent = mail.htmlContent.replaceAll("%Venue%", prgProp.venueProp.displayName + " - " + prgProp.venueProp.address);
		mail.htmlContent = mail.htmlContent.replaceAll("%TransactionId%", regProp.transactionId);
		mail.htmlContent = mail.htmlContent.replaceAll("%InvoiceNumber%", 
				Invoice.getInvoiceNo(prgProp.programTypeProp.displayName, prgProp.groupProp.displayName, registrationId));
		mail.htmlContent = mail.htmlContent.replaceAll("%Amount%", prgProp.ccy + " " + prgProp.fee);
		
		String htmlSessions = "";
		for(int i = 0; i < prgProp.batch1SessionTimings.size(); i++) {
			
			String session = prgProp.batch1SessionTimings.get(i).replaceAll("Z", ""); //TODO: Remove Z from data
			String[] timings = session.split(">");
			String startTime, endTime, day;

			try {
				SimpleDateFormat ftSrc = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
				SimpleDateFormat ftDay = new SimpleDateFormat("EEE d MMM");
				SimpleDateFormat ftTime = new SimpleDateFormat("h:mm a");
				
				Date dtStart = ftSrc.parse(String.valueOf(timings[0]));
				day = ftDay.format(dtStart);
				startTime = ftTime.format(dtStart);
				endTime = ftTime.format(ftSrc.parse(String.valueOf(timings[1])));
				htmlSessions += "<tr><td>" + day + "</td><td>" + startTime + " to " + endTime + "</td></tr>\n";
			}
			catch (Exception ex) {
				logger.warning(ex.toString());				
			}			
		}
		
		mail.htmlContent = mail.htmlContent.replaceAll("%Sessions%", htmlSessions);
		
		return mail;		
	}
}
